{extend name="$BASE_POPUP" /}
{block name="body"}
<link rel="stylesheet" type="text/css" href="{:ADDON_PUBLIC}/css/css.css" />


<div class="pic_head">
    <input type="file" style="display: none" id="file-selector" name="">
    <a id="selectfiles" href="javascript:void(0);" class='btn webuploader-pick'>上传图片</a>
</div>
<div class="pic_resources">
    <div class="img_pick" id="js_grid">               
    </div>
</div>       
<div class="pagination-box" id="js_pagination">
    <span class="pagination-info">显示 <span class="js_from">0</span> 到 <span class="js_to">0</span> 项，共 <span class="js_total">0</span> 项</span>
    <div id="js_page" style="text-align:center"></div>
</div> 


{/block}
{block name="script"}
<script type="text/javascript" src="__STATIC__/jquery/jquery.twbsPagination.js"></script>   
<!-- <script type="text/javascript" src="__STATIC__/webuploader/webuploader.js"></script> -->
<script src="\static\user\js\cos-js-sdk-v5.min.js"></script>
<script type="text/javascript">
    var folder = "{$folder}";
    var checktype = "{$checktype}"; 
    var is_cut="{$is_cut}";
    var limit_num = "{$limit_num}"; //限制张数
    var first = true;
    var pic_choosed = [];//记录选择的图片

    function ok() {
        var r = $(".img_pick ul li.selected");
        var path = "";
        for (var i = 0; i < r.length; i++) {
            if (i > 0)
                path += ",";
            path += $(r[i]).find("img").attr("data-path");
        }
        return path;
    }
    
    
    function hasSelected(id) {
        var match_str = ',' + id + ',';
        var ids_str = '';
        for (var k in pic_choosed) {
            if (ids_str != '')
               ids_str += ','; 
            ids_str += pic_choosed[k].id;
        }
        ids_str = ',' + ids_str + ',';
        if (ids_str.indexOf(match_str) >= 0) {
            return true;
        } else {
            return false;
        }
    }
    $("#js_grid").on("click", ".js_delete", function (e) {
        var that = this;
        confirm("删除后不可恢复，确认要删除吗？", function () {            
            var url = getURL("del");
            var id=$(that).attr("data-id");
            $.getJSON(url, {id: id}, function (json) {                
                if (json.success)
                    location.reload();
                else
                    alert(json.message);
            });
        });
        e.stopPropagation();
    });
    $(".img_pick").on("click", " ul li", function () {
        var item = new Object();
        if (checktype == "2") {
            //多选
            if ($(this).hasClass("selected")) {
                $(this).removeClass("selected");
                for (var key in pic_choosed) {
                    if (pic_choosed[key].id == item.id) {
                        pic_choosed.splice(key,1);
                        break;
                    }
                }
            } else {
                //pic_choosed.length 已选数量
                //limit_num 可选数量限制
                if (limit_num == '' || pic_choosed.length < limit_num) {
                    $(this).addClass("selected");
                    pic_choosed.push(item);
                } else {
                    alert('达到可选图片数量上限');
                }
            }
        } else {
            //单选
            $(".img_pick ul li").removeClass("selected");
            $(this).addClass("selected");
            pic_choosed = [];
            pic_choosed.push(item);
        }
    });
    window.onload = function () {
        var tips = parent._upload_tips;
        if (tips) {
            $("#_tips").html(tips);
        }
    };

    var Bucket = 'haiwan-1259625632';
    var Region = 'ap-chengdu';
    $('#selectfiles').click(function(){
        $('#file-selector').click();
    })
    // 初始化实例
    var cos = new COS({
        getAuthorization: function (options, callback) {
            var url = getURL("loadTencentAccess");
            var xhr = new XMLHttpRequest();
            xhr.open('GET', url, true);
            xhr.onload = function (e) {
                try {
                    var data = JSON.parse(e.target.responseText);
                } catch (e) {
                }
                callback({
                    TmpSecretId: data.credentials && data.credentials.tmpSecretId,
                    TmpSecretKey: data.credentials && data.credentials.tmpSecretKey,
                    XCosSecurityToken: data.credentials && data.credentials.sessionToken,
                    ExpiredTime: data.expiredTime,
                });
            };
            xhr.send();
        }
        ,FileParallelLimit: 1
        ,ProgressInterval:1000
    });
    function checkImg(tv_id){
        var index= tv_id.lastIndexOf(".");
        tv_id=tv_id.substring((index+1));
        var videolist = ['jpg', 'jpeg', 'png'];
        result = videolist.some(function (item) {
          return item == tv_id;
        });
        return result;
    }
    function upload_file(data,name,size){
        // console.log(data)
        // console.log(JSON.stringify(data))
        $.ajax({
            type: "POST",
            dataType: "json",
            url: getURL("tencentUpload"),
            data: {filename: name,filesize: size,filepath:'https://'+data.Location,folder:folder},    //视情况将base64的前面字符串data:image/png;base64,删除
            cache: false,
            success: function(data) {
                if(data['success']){
                    window.location.reload();
                }else{
                    alert(data['msg'])
                    hideLoading();
                }
            },
            error: function(XMLHttpRequest, textStatus, errorThrown) {
                hideLoading();
                alert("上传失败，请检查网络后重试");
            }
        });
    }
    // 监听选文件
    document.getElementById('file-selector').onchange = function () {
        var file = this.files[0];
        if (!file) return;
        var res = checkImg(file.name);
        if(!res){
            alert("不是指定图片格式,重新选择"); 
            return;
        }
        showLoading("上传数据中...");
        if (file.size > 1024 * 1024) {
            cos.sliceUploadFile({
                Bucket: Bucket, // Bucket 格式：test-1250000000
                Region: Region,
                Key: file.name,
                Body: file,
                onTaskReady: function (tid) {
                    TaskId = tid;
                },
                onHashProgress: function (progressData) {
                    // logger.log('onHashProgress', JSON.stringify(progressData));
                },
                onProgress: function (progressData) {
                    // logger.log('onProgress', JSON.stringify(progressData));
                },
            }, function (err, data) {
                // logger.log(err || data);
                if(data.statusCode==200){
                    upload_file(data,file.name,file.size)
                }
            });
        } else {
            cos.putObject({
                Bucket: Bucket, // Bucket 格式：test-1250000000
                Region: Region,
                Key: file.name,
                Body: file,
                onTaskReady: function (tid) {
                    TaskId = tid;
                },
                onProgress: function (progressData) {
                    // logger.log(JSON.stringify(progressData));
                },
            }, function (err, data) {
                // logger.log(err || data);
                if(data.statusCode==200){
                    upload_file(data,file.name,file.size)
                }
            });
        }
    };

    var pageSize = 18;
    var first = true;
    $(function () {
        if (limit_num) {
            limit_num = parseInt(limit_num);
        }
    
        loadData(1);
    });
    function loadData(page) {
        showLoading("加载数据中...");
        var url = getURL("loadList");
        $.getJSON(url, {page: page, pageSize: pageSize, folder: folder}, function (json) {
            bindData(page, json);
            if (first) {
                var totalPage = Math.ceil(json.total / pageSize);
                $('#js_page').twbsPagination({
                    totalPage: totalPage,
                    visiblePage: 5,
                    onPageClick: function (event, page) {
                        if (!first)
                            loadData(page);
                    }
                });
                first = false;
            }
            hideLoading();
        });
    }

    function bindData(page, data) {
        var html = '';
        if (data.total > 0) {
            html += '<ul>';
            var len = data.rows.length;
            for (var i = 0; i < len; i++) {
                var pic = data.rows[i];
                html += '<li>';
                html += '<div class="img_box"><img data-path="' + pic['file_path'] + '" src="'+pic['file_path'] + '"/></div>';
                html += '<span class="lbl_content">' + pic['file_name'] + '</span>';
                html += ' <a href="javascript:;" data-id="' + pic['id'] + '" class="del_pic"><i data-id="' + pic['id'] + '" class="icon wb-trash js_delete right"></i></a>';
                html += '<div class="selected_mask"><div class="selected_mask_inner"></div><div class="selected_mask_icon"><i class="icon wb-check"></i></div></div>';
                html += '</div>';
                html += '</li>';
            }
            html += '</ul>';
            $("#js_pagination").show();
            var from = (parseInt(page) - 1) * parseInt(pageSize) + 1;
            var to = from + len - 1;
            if (data.total < 1)
                from = to = 0;
            $(".js_from").html(from);
            $(".js_to").html(to);
            $(".js_total").html(data.total);
        } else {
            $("#js_pagination").hide();
            html = ' <div style="text-align:center;margin-top:100px">无相关素材信息!</div>';
        }
        $("#js_grid").html(html);
    }
</script>
{/block}